import 'package:flutter/material.dart';
import 'package:play_android/com/zhihaoliang/const/AppApi.dart';
import 'package:play_android/com/zhihaoliang/http/HttpException.dart';
import 'package:play_android/com/zhihaoliang/base/BaseRepository.dart';
import 'package:play_android/com/zhihaoliang/http/ResultData.dart';
import 'package:play_android/com/zhihaoliang/http/HttpRequest.dart';
import 'package:play_android/com/zhihaoliang/play/common/article/ArticleData.dart';
import 'package:play_android/com/zhihaoliang/play/common/article/ArticleItem.dart';
import 'package:play_android/com/zhihaoliang/play/common/article/ArticleModel.dart';

///  ***************************************************************************
///  "文章列表数据"请求处理
///  ***************************************************************************

class ArticlePresenter extends BaseRepository<List<ArticleItem>> {
  ArticleCallBack _callBack;

  int _curPage = 0;

  String url;

  Map<String, String> map;

  ArticlePresenter(this._callBack, this.url, [this.map]);

  ArticleData _homeData;

  loadFrist() async{
    _curPage = 0;
    _loadData(initUrl());
  }

  load() {
    _loadData(initUrl());
  }

  String initUrl() {
    String url = this.url;
    return url += "$_curPage/json";
  }

  _loadData(String url) {
    fetch(url, map)
        .then((homeData) => _callBack.onLoadArticleComplete(homeData))
        .catchError((onError) => _callBack.onLoadArticleError(onError));
  }

  bool isEnd() {
    if (_homeData == null) {
      return true;
    }

    if (_homeData.offset == null ||
        _homeData.size == null ||
        _homeData.total == null) {
      return true;
    }
    return _homeData.offset + _homeData.size >= _homeData.total;
  }

  bool isFrist() {
    return _curPage == 0;
  }

  @override
  List<ArticleItem> fetchModel(Map<String, dynamic> map) {
    ArticleModel homeModel = ArticleModel.fromJson(map);
    ArticleData homeData = homeModel.data;
    if (_homeData == null || isFrist()) {
      _homeData = homeData;
    } else {
      _homeData.datas.addAll(homeData.datas);
    }

    if (isEnd()) {
      ArticleItem homeItem = ArticleItem();
      homeItem.type = ArticleItem.END;
      _homeData.datas.add(homeItem);
    }
    _curPage++;
    return _homeData.datas;
  }

  @override
  Future<ResultData> fetchResultData(
      [String url, Map<String, dynamic> map]) async {
    if (url.contains(AppApi.ARTICLE_LIST) || url.contains(AppApi.COLLECT_LIST)) {
      return await HttpRequest().get(url, map);
    }
    return await HttpRequest().post(url, map);
  }
}

abstract class ArticleCallBack {
  void onLoadArticleComplete(List<ArticleItem> homeData);

  void onLoadArticleError(HttpException httpException);
}
